#!/usr/bin/env python
#-*- coding:utf-8 -*-

from model.get_db import get_db
from model.common import not_empty
from bson.objectid import ObjectId
from pymongo import DESCENDING
from setting import page_size

__all__=['get_articles','get_categories', 'get_category', 'get_comments', 'get_artdate']
db = get_db()
POST = 'posts'
CATE = 'categories'
COMM = 'comments'


def get_articles(artid = None, index = 1, size = page_size, addviews=False, **kargs):
    '''
    获取文章,
    `index` : 分页索引
    `size`  : 每页文章数
    `artid` : 如果提供artid则返回单个文章
    `**kargs` : 其他条件
    '''
    if kargs.get('categories','') == '未分类':
        kargs['categories'] = []

    if artid:
        result = db[POST].find_one({"_id":ObjectId(artid)})
        _c = []
        for cate in result.get('categories', []):
            _c.append(dict(name=get_category(cate).get('name'), _id=cate))
        result['categories'] = _c
        if addviews:
            db[POST].update({"_id":ObjectId(artid)},{"$inc":{"views":1}})
        return result
    else:
        result = db[POST].find(kargs).skip((index-1) * size).limit(size).sort("_id", DESCENDING)
        if result:
            _r = []
            for r in result:
                _c = []
                for cate in r.get('categories', []):
                    _c.append(dict(name=get_category(cate).get('name'), _id=cate))
                r['categories'] = _c
                _r.append(r)
            result = _r
        else:
            result = []
        return result if result else [], db[POST].find(kargs).count()


def get_categories(index = 1, size = page_size):
    '''
    获取分类目录
    '''
    result = list(db[CATE].find().skip((index-1) * size).limit(size).sort("_id", DESCENDING))
    return result if result else []


def get_category(_id):
    not_empty(_id)
    return db[CATE].find_one({"_id":ObjectId(_id)})


def get_comments(artid = None, index = 1, size = page_size):
    '''
    获取评论
    `artid`: 如果有则按照artid获取评论,否则全部获取
    '''
    if artid:
        result = list(db[COMM].find({"artid":artid}).skip((index-1)*size).limit(size))
        count = db[COMM].find({"artid":artid}).count()
    else:
        result = list(db[COMM].find().skip((index-1)*size).limit(size).sort("_id", DESCENDING))
        count = db[COMM].find().count()

    _a = []
    for r in result:
        article = get_articles(artid=r.get('artid'))
        r['title'] = article.get('title')
        _a.append(r)
    return _a, count

    
def get_artdate():
    '''
    获取有文章月份归档
    '''
    
    # 便利数据库获取所有文章的月份
    tmpdates = []
    for date in db[POST].find():
        fulldate = date['date']
        realdate = str(fulldate.year) + '-' + str(fulldate.month)
        tmpdates.append(realdate)
    
    # 去掉重复的
    dates = list(set(tmpdates))
    
    return dates
